import React, { Fragment, useEffect, useState } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { Card,Table,Form, Input, Modal, message,Button,Popconfirm, Select,Upload } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import {queryRequest,editRequest,deleteRequest,addRequest} from './services';


const Index = () => {
  const [currentInfo,setCurrentInfo] = useState<{show:boolean,info:any}>({show:false,info:{}});
  const [dataSource,setDataSource] = useState<any[]>([]);
  const [form] = Form.useForm();
  const [fileList,setFileList] = useState<any[]>([]);//已上传的午餐图片
  const [videoList,setVideoList] = useState<any[]>([]);//已上传的视频
  const columns = [
    {
      title: '名称',
      dataIndex: 'name',
    },
    {
      title: '图片',
      dataIndex: 'img',
      render:(url:string) => <img style={{width:200}} src={url} alt="午餐图片"/>
    },
    {
      title: '创建时间',
      dataIndex: 'create_time',
    },
    {
      title: '操作',
      dataIndex: 'id',
      render: (id:number,record:any) => <Fragment>
        <Button type='link' onClick={() => { handleEdit(record)}}> 编辑 </Button>
        <Popconfirm
          title="确定删除吗？"
          onConfirm={()=>{ handleDelete(id)}}
        >
          <Button danger  type='link'>删除</Button>
        </Popconfirm>
      </Fragment> 
    },
  ];
  //初始化
  useEffect(() => {
    getList();
  },[]);
  //请求列表接口---请求
  const getList = () => { 
    queryRequest().then((res:any) => {
      setDataSource(res)
      console.log(res)
    });
  }
  //提交编辑/新增---请求
  const handleOK = () => {
    form.validateFields().then(values => {
      let params = {...values};
      let request = addRequest;
      if(currentInfo.info.id){
        params['id'] = currentInfo.info.id;
        request = editRequest;
      }
      request(params).then((res) => {
        if(res.success){
          message.success('修改成功');
          setCurrentInfo({show:false,info:{},});
          getList();
        }
      })
    }).catch(info => {
      console.log(info)
    })
  }
  //删除---请求
  const handleDelete = (id:any) => {
    deleteRequest({id:id}).then(res => {
      if(res.success){
        message.success('删除成功');
        getList();
      }
    })
  }
  //编辑按钮
  const handleEdit = (record:any) => {
    setCurrentInfo({show:true,info:record});
    setFileList([{uid:'-1',name:'image.png',status:'done',url:'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png'}])
    form.setFieldsValue({
      position: record.position,
      img: [{uid:'-1',name:'image.png',status:'done',url:'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png'}],
      url: record.url,
      sort: record.sort
    })
  }
  //添加按钮
  const handleAdd = () => {
    setCurrentInfo({show:true,info:{}});
    form.resetFields();
    setFileList([]);
    setVideoList([])
  }
  const normFile = (e: any) => {
    if (Array.isArray(e)) {
      return e;
    }
    return e && e.fileList;
  };
  const handleChangeFileList = (e:any) => {
    setFileList(e.fileList)
  }
  const handleChangeVideoList = (e:any) => {
    setVideoList(e.fileList)
  }

  return <PageHeaderWrapper title={false}>
    <Card>
      <Table
        rowKey='id'
        columns={columns}
        dataSource={dataSource}
        pagination={false}
        style={{marginBottom:10}}
      />
      <Button type='dashed' onClick={handleAdd} block>添加banner</Button>
    </Card>
    <Modal
      title={currentInfo.info.id?'编辑':'新增'}
      visible={currentInfo.show}
      onCancel={()=>{
        form.resetFields();
        setCurrentInfo({show:false,info:{}});
        setFileList([]);
        setVideoList([]);
      }}
      destroyOnClose={true}
      onOk={handleOK}
    >
      <Form
        labelCol={{span:6}}
        wrapperCol={{span:18}}
        form={form}
      >
        <Form.Item label='名称' name="name" rules={[{required: true, message: '请输入名称'}]}>
          <Input/>
        </Form.Item>
        <Form.Item
          shouldUpdate={true} 
          label='午餐图片' 
          name="img" 
          valuePropName='fileList' 
          getValueFromEvent={normFile} 
          rules={[{required: true, message: '请上传图片'}]}
        >
         <Upload name="logo" action="/upload.do" listType="picture-card" onChange={handleChangeFileList}>
           {
             fileList.length <1 &&
             <div>
                <PlusOutlined />
                <div style={{ marginTop: 8 }}>上传图片</div>
              </div>
           }
          </Upload>
        </Form.Item>
        <Form.Item
          shouldUpdate={true} 
          label='详情图片集' 
          name="detail_img" 
          valuePropName='fileList' 
          getValueFromEvent={normFile} 
          rules={[{required: true, message: '请上传图片'}]}
        >
         <Upload name="logo" action="/upload.do" listType="picture-card">
          <div>
            <PlusOutlined />
            <div style={{ marginTop: 8 }}>上传图片</div>
          </div>
          </Upload>
        </Form.Item>
        <Form.Item
          shouldUpdate={true} 
          label='详情视频' 
          name="detail_video" 
          valuePropName='fileList' 
          getValueFromEvent={normFile}
        >
         <Upload name="logo" action="/upload.do" onChange={handleChangeVideoList}>
           {videoList.length <1 && <Button>上传视频</Button>}
          </Upload>
        </Form.Item>
      </Form>
    </Modal>
  </PageHeaderWrapper>
}

export default Index;